package xml;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxTest {
	public static void main(String[] args) throws ParserConfigurationException,
			SAXException, IOException {
		test();
	}

	private static void test() throws ParserConfigurationException,
			SAXException, IOException {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		parser
				.parse(
						new File(
								"/home/tarena/0code/xml/sd1010_xml_day01_all.zip_FILES/test.html"),
						new MyHandler());
	}

	static class MyHandler extends DefaultHandler {
		public void startDocument() throws SAXException {
			// System.out.println("<?xml version='1.0'?>");
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			//通过元素名、属性名得到属性值
			if("a".equals(qName)){
				System.out.println(attributes.getValue("href"));
			}
			
			//通过属性名得到属性值
//			for (int i = 0; i < attributes.getLength(); i++) {
//				if("href".equals(attributes.getQName(i)))	{
//					System.out.println(attributes.getValue(i));
//				}
//			}
			
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			// System.out.println("</"+qName+">");
		}

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			String s = new String(ch, start, length);
			// System.out.println(s);
		}
	}
}
